import { login, getAvatar } from '@/api'

const state = {
  token: localStorage.getItem('token') | [],
  userInfo: localStorage.getItem('userInfo') || {},
  avatar: JSON.parse(localStorage.getItem('avatar')) || null,
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  setAvatar: (state, avatar) => {
    state.avatar = avatar
  },
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((res) => {
          if (res.code == 200) {
              userInfo.name = res.data.employeeName
              userInfo.positionName = res.data.positionName
              userInfo.userId = res.data.userId
              userInfo.gender = res.data.gender
              commit('setUserInfo', userInfo)
              commit('SET_TOKEN', res.data.accessToken)
              localStorage.setItem('userInfo', JSON.stringify(userInfo))
              localStorage.setItem('token', res.data.accessToken)
              resolve()
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  setAvatar({ commit }) {
    return new Promise((resolve, reject) => {
      getAvatar()
        .then((res) => {
            // console.log('res',res)
            const avatar = res
            // console.log("avatar",avatar)
            commit('setAvatar', avatar)
            localStorage.setItem('avatar', JSON.stringify(avatar))
            resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('setRoutes', '')
      commit('setButtons', '')
      commit('setUserInfo', '')
      commit('setAvatar', '')
      localStorage.removeItem('token')
      localStorage.removeItem('buttons')
      localStorage.removeItem('avatar')
      resolve()
    })
  },
}

 function  avatar(){
  let avatar
    // getAvatar().then(res => {
    //   avatar = res.data
    //   // console.log("getAvatar",getAvatar)
    // })
    getAvatar().then(res => {
      avatar = res.data
    })
    return avatar
    
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
